(function () {
	/**
	 * 定义$代表jQuery对象
	 */
	var $ = jQuery;
	/**
	 * 当前用户userid
	 */
	var userId = "";
	/**
	 * 当前用户userName
	 */
	var userName="";
	/**
	 * 当前用户对象
	 */
	var userInfoObj;
	/**
	 * 座席、营业员
	 */
	var jobCode="";
	/**
	 * 群组ID
	 */
	var groupIdCode="";
	/**
	 * socket id
	 */
	var sessionid="";
	
	/**
	 * 闪烁效果
	 */
	var visitIsIn = "msgFlash1";
    var iFlash = setInterval(function () {
        if (visitIsIn === "msgFlash1") {
            $('.' + visitIsIn).removeClass(visitIsIn).addClass("msgFlash2");
            visitIsIn = "msgFlash2";
        } else {
            $('.' + visitIsIn).removeClass(visitIsIn).addClass("msgFlash1");
            visitIsIn = "msgFlash1";
        }

    }, 500);

    var timerArr;
    var title_text = $("title").text();
    $.extend({
    	/**
		 * 调用方法
		 * $.blinkTitle.show();
		 * $.blinkTitle.clear();
		 */
		blinkTitle : {
			show : function() {	//有新消息时在title处闪烁提示
				var step=0, _title = title_text;
	
				var timer = setInterval(function() {
					step++;
					if (step==3) {step=1};
					if (step==1) {document.title='【　　　】'+_title};
					if (step==2) {document.title='【新消息】'+_title};
				}, 500);
				timerArr = [timer, _title];
			},
			/**
			 * @param timerArr[0], timer标记
			 * @param timerArr[1], 初始的title文本内容
			 */
			clear : function() {	//去除闪烁提示，恢复初始title文本
				if(timerArr) {
					clearInterval(timerArr[0]);	
					document.title = timerArr[1];
				};
			}
		}
	});
	
    /**
     * ready
     */
	$(function(){
		var CurrentActive;
    	$(window).focus(function() {
    	    //处于激活状态
    		$.blinkTitle.clear();
    		CurrentActive = false;
    	});
    	$(window).blur(function() {
    	    //处于未激活状态
    		CurrentActive = true;
    	});
		/**
		 * 页面获取登录用户对象
		 */
		userInfoObj = eval("(" + $("#hid_userInfo").val() + ")");
		userId = userInfoObj.id;
		userName = userInfoObj.username;
		jobCode = userInfoObj.jobCode;
		if(jobCode == '1'){
			$("#jumpLink").append("<a href=\"seat?baseId="+userId+"\" target=\"_blank\">进入座席</a>");
		}
		if(jobCode == '0'){
			$("#jumpLink").append("<a href=\"visit?baseId="+userId+"\" target=\"_blank\">进入营业员</a>");
		}
		
		/**
		 * 连接大厅的socket
		 */
		var talkSocket = io.connect('http://' + _host + ':' + _port + '/talk');
		/**
		 * 连接大厅后，触发connChatRoom方法</br>
		 */
		var connectHandler = function() {
			/**
			 * 监听leaveInfo，验证重复登录
			 * 监听userList，首次进入监听，获取所有在线用户
			 * 监听addUserToList，坐席已在线，当有新用户进入时，刷新列表
			 */
			talkSocket.emit("connTalkRoom", userId);
	    };
	    /**
	     * 重复登录处理-[leaveInfo]
	     */
	    var leaveInfoHandler = function(_leaveInfoMsg){
	    	output("<span style=\"color:red\">"+_leaveInfoMsg+"</span>", "lvEdit", "系统");
	    	var targetId = $("#hid_current_visitId").val();
	    	output("<span style=\"color:red\">"+_leaveInfoMsg+"</span>", targetId, "系统");
	    	$("#visitInfo").empty();
	    	$("#userlist").empty();
	    	$("#seatConnectlist").empty();
	    	
	    };
	    /**
	     * 首次进入监听，获取所属群组-[groupToList]
	     */
	    var addGroupToListHandler = function(_glstMap){
	    	sessionid = talkSocket.socket.sessionid;
	    	var glstObj = eval("(" + _glstMap + ")");
	    	$("#grouplist").empty();
	    	if (null == glstObj){
	    		return ;
	    	}
	    	$.each(glstObj.groupChats,function(key,values){
	    		var group = glstObj.groupChats[key];
	    		$("#grouplist").append($.format(groupLi,group.groupid,group.groupname));
	    		//为群组绑定事件
	    		var $groupLi = $('li.li_id_group_' + group.groupid);
		    	$groupLi.on('click',groupRequestHandler);
	    	}); 
	    };
	    /**
	     * 已在线，当有新用户进入时，刷新列表-[addUserToList]
	     */
	    var addUserToListHandler = function(_userlist){
	    	var userlist = eval("(" + _userlist + ")");
	    	$("#userlist").empty();
	    	for(var i = 0; i<userlist.length;i++){
	    		var userVo = userlist[i];
	    		$("#userlist").append($.format(userLi,userVo.id,userVo.username,userVo.dept));
	    	};
	    };
	    /**
	     * 显示更新同时在线人数
	     */
	    var userCountHandler = function(_count){
	    	$("#userCount").html("当前群组在线人数：" + _count);
	    };
	    /**
	     * 离线，刷新用户列表-[removeUserToList]
	     */
	    var removeUserToListHandler = function(_userVo){
	    	var userVo = eval("(" + _userVo + ")");
	    	var _userId = userVo.id;
	    	var $userLi = $('li.userChatItems_' + _userId);
	    	$userLi.remove();
	    };
	    /**
	     * 监听接收消息，所有监听到的消息，都是发给自己的-[receiveMessage]
	     */
	    var receiveMessageHandler = function(_message){
	    	var chatObj = eval("(" + _message + ")");
	    	if(chatObj.groupId != groupIdCode){
	    		//收到消息消息列表闪烁
	    		var $groupLi = $("li.li_id_group_" + chatObj.groupId);
	    		$groupLi.addClass(visitIsIn);
	    	}
    		output(chatObj.message, chatObj.groupId, chatObj.fromUserName);
    		var ue = UE.getEditor('editor_'+chatObj.groupId);
        	ue.setContent("");
        	//新消息闪烁
        	if (CurrentActive && chatObj.fromUserId != userId) {
        		//先清理，防止重复操作
        		$.blinkTitle.clear();
        		$.blinkTitle.show();
			}
	    };
	    /**
	     * 打印系统消息
	     */
	    var userMessageHandler = function(chatJson){
	    	var chatObj = eval("(" + chatJson + ")");
	    	output(chatObj.message,chatObj.groupId,"系统");
	    };
	    /**
	     * resize的时候，重新初始化编辑器
	     */
	    $(window).resize(function(){
	    	initUE(groupIdCode);
	    });
	    /**
	     * 显示截图
	     */
	    var snapscreenPathHandler = function(jsonInfo){
	    	var snapObj = eval("(" + jsonInfo + ")");
	    	var snapscreenPath = snapObj.imgSrc;
	    	var userName = snapObj.fromUserName;
	    	var targetId = groupIdCode;
	    	var ue = UE.getEditor('editor_'+targetId);
	    	ue.setContent(snapscreenPath);
	    };
		
		/**
	     * 群组请求连接-[groupRequest]
	     */
	    var groupRequestHandler = function(){
	    	var $this = $(this);
	    	groupIdCode = $this.attr("groupid");
	    	talkSocket.emit("getGroupUserToList",groupIdCode,userId);
	    	//取消列表闪烁
    		var $groupLi = $("li.li_id_group_" + groupIdCode);
    		$groupLi.removeClass(visitIsIn);
	    	//取消当前会话状态
	    	var $groupStyle = $('li.li_id_group_style');
	    	$groupStyle.removeClass('selected');
	    	//设置状态为当前会话
	    	$this.addClass("selected");
	    };
	    
	    /**
	     * 历史按钮事件
	     */
	    var historyButClick = function(){
	    	var $this = $(this);
	    	var groupid = $this.attr("groupid");
	    	var hisDate = $("#his_date_" + groupid);
	    	if(!hisDate.val()){
	    		alert("请选择日期");
				return;
	    	}
	    	talkSocket.emit('talkHistoryInfoShow',groupid,hisDate.val());
	    };
	    
	    /**
	     * 适配器窗口
	     */
	    var adapterWindowsHandler = function(_groupObj){
	    	var $groupOjb = eval("(" + _groupObj + ")");
	    	var $groupWindows = $('div.chatContainer_' + $groupOjb.groupid);
	    	if($groupWindows.length == 0){
	    		//显示对话div
		     	var $templateContent = $('#chatTemplate');
		        var data = [
		            {uid: $groupOjb.groupid}
		        ];
		        $templateContent.tmpl(data).appendTo($('#chatContainers'));
		        var $defaultContainer = $("#defaultChatContainer");
			    $defaultContainer.hide();
			    //绑定发送按钮事件
		    	var $sendButton = $("input.l_service_cz_button_" + $groupOjb.groupid);
		    	$sendButton.on('click',sendMessageHandler);
		    	
		    	//快捷回复加载
		    	var $ksButton =  $(".ksButton_" + $groupOjb.groupid);
		    	if(jobCode == '1'){//非座席不加载快捷回复
		    		$ksButton.on('click',ksButtonClick);
		    		//加载常用回复
		    		talkSocket.emit("autoReply");
		    	} else {
		    		$ksButton.hide();
		    	}
		    	
		    	//绑定历史按钮事件
		    	var $history = $("#his_btn_"+$groupOjb.groupid);
		    	$history.on('click',historyButClick);
		    	
			    $groupWindows = $('div.chatContainer_' + $groupOjb.groupid);
	    	} else {
	    		//如果窗口可见跳出方法
	    		var temp = $groupWindows.is(":visible");
	    		if (temp) {
					return ;
				}
	    	}
	    	$(".chatContainer").hide();
	    	$groupWindows.show();
	    	
	    	//更新titleInfo
	    	$titleInfo = $("#titleInfo_" + $groupOjb.groupid);
	    	$titleInfo.empty();
	    	var $titleInfoTemplate = $("#titleInfoTemplate");
	    	var titleInfoText = [
	    	    {groupname:$groupOjb.groupname}
	    	];
	    	$titleInfoTemplate.tmpl(titleInfoText).appendTo($titleInfo);
	    	$(window).resize();
	    };
	    
	    //常用回复
	    var ksButtonClick = function(){
	    	$this = $(this);
	    	var id = $this.attr("groupid");
	    	$(".hfls_"+id).toggle();
	    };
	    
	    var replyClick = function(){
	    	var $this = $(this);
	    	var _groupid = $this.parent('div.hfls').attr("groupid");
	    	var ue = UE.getEditor('editor_'+_groupid);
	    	ue.setContent($this.attr("title"),true);
	    };
	    
	    /**
	     * 展示常用回复
	     */
	    var autoReplyHandler = function(_replys){
	    	var id = groupIdCode;
	    	var $replyObj = eval("(" + _replys + ")");
	    	$("#replyArea_"+id).empty();
	    	for(var i = 0; i<$replyObj.length;i++){
	    		var replyObj = $replyObj[i];
	    		$("#replyArea_"+id).append($.format(replyP,replyObj.title,replyObj.content,replyObj.id,id));
	    		$("#"+replyObj.id+id).on('click',replyClick);
	    	};
	    };
	    
	    /**
	     * 发送消息-[sendMessage]
	     */
	    sendMessageHandler = function(){
	    	var _groupid = groupIdCode;
	    	var visitUE = UE.getEditor('editor_' + _groupid);
	    	
	    	var message = visitUE.getContent();
	    	if(!message){
	    		alert("请不要发送空消息！");
	    		return;
	    	}
	    	var jsonObject = {'@class': 'com.zx.chatroom.vo.Chat',
	    			fromUserId : userId, 
	    			fromUserName : userName, 
	    			groupId : _groupid,
					message : message};
			talkSocket.json.send(jsonObject);
			//清除消息闪烁
	    	$.blinkTitle.clear();
	    };
	    
	    /**
		 * 截图插件
		 */

				
		function plugin0() {
			return document.getElementById('plugin0');
		}

		plugin = plugin0;

		function snapshot() {
			if (undefined == plugin().snapshot) {
				$("#dialog_info").show();
			} else {
				if (groupIdCode) {
					plugin().snapshot($("#localAddr").val(),"/chatroomV2/snapscreenUp/" + userId + "/" + groupIdCode + "/talk", $("#localPort").val());
				}
			}
		}
		$(document).off(".snapshotButtonClick");
		$(document).on("click.snapshotButtonClick", ".snapshotButton", snapshot);
		$(document).off(".dialogCloseClick");
		$(document).on("click.dialogCloseClick", ".t_pic", function() {
			$("#dialog_info").hide();
		});
	    
		/**
		 * 页面加载完成，连接大厅
		 */
		talkSocket.on('connect',connectHandler);
		/**
		 * 监听重复登录
		 */
		talkSocket.on('leaveInfo',leaveInfoHandler);
		/**
		 * 加载所属群组信息
		 */
		talkSocket.on('addGroupToList',addGroupToListHandler);
		/**
		 * 当有新用户进入时，刷新列表
		 */
		talkSocket.on('addUserToList',addUserToListHandler);
		/**
		 * 监听同时在线人数变化-[addUserToList]
		 */
		talkSocket.on('userCount',userCountHandler);
		/**
		 * 离线
		 */
		talkSocket.on('removeUserToList',removeUserToListHandler);
		/**
		 * 适配器窗口
		 */
		talkSocket.on('adapterWindows',adapterWindowsHandler);
		/**
		 * 接收消息
		 */
		talkSocket.on('receiveMessage',receiveMessageHandler);
		/**
		 * 打印系统消息
		 */
		talkSocket.on('userMessage',userMessageHandler);
		/**
		 * 上传截图
		 */
		talkSocket.on("snapscreenPath",snapscreenPathHandler);
		/**
		 * 加载常用回复
		 */
		talkSocket.on('autoReply',autoReplyHandler);
		/**
		 * 显示历史记录
		 */
		talkSocket.on('hisInfo',function(charLog){
			//放到隐藏div里
			var _visitId = groupIdCode;
			$("#lvEdit_"+_visitId).removeClass("l_serviceHidden");
			
			var $closeBtn = $(".serviceList_close_btn_"+_visitId);
			$("#lvEdit_"+_visitId).html("");
			$("#lvEdit_"+_visitId).html("<span style ='color:red'>历史记录</span><br/>"+charLog);
			$closeBtn.removeClass("serviceList_close_btn");
			$closeBtn.addClass("serviceList_close_btn_show");
			$("#lvEdit_"+_visitId).show();
			$closeBtn.show();
			$(document).off(".closeBtn_"+_visitId);
			$(document).on('click.closeBtn_'+_visitId,'.serviceList_close_btn_'+_visitId,function(){
				$("#lvEdit_"+_visitId).hide();
				$closeBtn.hide();
			});
			
		});
		/**
		 * 重复登页面清除
		 */
		talkSocket.on('userLeaveClearPageInfo',function(_sessionid){
			if(sessionid == _sessionid){
				$("#jumpLink").html("");
				$("#grouplist").empty();
				$("#userlist").empty();
				//隐藏现用聊天模板
				$('div.chatContainer_' + groupIdCode).hide();
				//回显默认聊天模板
				$("#defaultChatContainer").show();
				//清除提示
				$("#userCount").html("");
			}
		});
	    /**
	     * resize的时候，重新初始化编辑器
	     */
	    $(window).resize(function(){
	    	initUE(groupIdCode);
	    });
	    /**
	     * 初始化UE
	     */
	    function initUE(id) {
	    	var _content;
	    	$("textarea[name='"+(UEDITOR_CONFIG.textarea?UEDITOR_CONFIG.textarea:'editorValue')+"']").remove();
	    	var ue1;
	    	if(id){
	    		ue1 = UE.getEditor('editor_'+id);
	    	}else {
				ue1 = UE.getEditor('editor');
			}
	    	
	    	if(ue1){
	    		_content = ue1.getContent();
	    		ue1.destroy();
	    	}
	    	var $bgArea = $(".l_service_bj_"+id);
	    	$bgArea.empty();
	    	var $editor;
	    	if(id){
	    		$editor = $("<div id = 'editor_"+id+"'></div>");
	    	}else{
	    		$editor = $("<div id = 'editor'></div>");
	    	}
	    	var _w;
	    	if(id){
	    		_w = $(".l_service_bj_"+id).width();
	    	}else{
	    		_w = $(".l_service_bj").width();
	    	}
	    	//console.log(_w-1);
			$editor.css({
				width:(_w-1),
				height:167
			});
			$bgArea.append($editor);
			if(id){
				setTimeout(function(){
					var ue = UE.getEditor('editor_'+id,{ 
						initialFrameWidth : (_w-1),
				        initialFrameHeight: 167,
				        basePath:basePath
					});
					ue.ready(function(){
						if(_content){
							ue.setContent(_content);
						}
					});
					
				},10);
			}else{
				setTimeout(function(){
					var ue = UE.getEditor('editor',{ 
						initialFrameWidth : (_w-1),
				        initialFrameHeight: 167,
				        basePath:basePath
					});
					ue.ready(function(){
						if(_content){
							ue.setContent(_content);
						}
					});
					
				},10);
			}
	    }
	});
	
	/**
	 * @param _message 输出信息
	 * @param _targetId 输出信息打印区域元素ID
	 * @param _userName 信息输出者NAME
	 */
	var output = function(_message, _targetId, _userName) {
        var currentTime = "<span class='time'>" + moment().format('HH:mm:ss') + "</span>";
        var element = $("<div>" + currentTime + " " + _message + "</div>");
        if (!_targetId) {
        	_targetId = "lsEdit";
        } else {
            element = $("<div>" + currentTime + " " + _userName + "：" + _message + "</div>");
        }
        $("#" + _targetId).append(element);
        scollToButtom(_targetId);
    };
    /**
	 * 聊天窗口div自动滚动至底部
	 */
	function scollToButtom(elementId) {
        $("#" + elementId).animate({
            scrollTop: $("#" + elementId)[0].scrollHeight
        }, 1000);
    }
}).call(this);

/**
 * 坐席列表li
 */
var userLi = "<li userid='{0}' class='userChatLi userChatItems_{0} li_id_{0}' title='{2}'><span class='linkChat' userid='{0}'>{1}({2})</span></li>";
/**
 * 群组列表li
 */
var groupLi = "<li groupid='{0}' class='userChatLi li_id_group_style userChatItems_{0} li_id_group_{0}' title='{1}'><span class='linkChat' groupid='{0}'>{1}</span></li>";
/**
 * 常用回复段落P
 */
var replyP = "<p id = '{2}{3}' title = '{1}'>{0}</p>";